import {Commit, createStore} from "vuex";
import axios, {AxiosRequestConfig} from "axios";
import {registerRuntimeCompiler} from "vue";
//封装get请求-Commit就是commit类型
const getAndCommit = async (
    url: string,
    mutationName: string,
    commit: Commit
) => {
    // commit('setLoading',true)//开始
    const {data} = await axios.get(url);
    commit(mutationName, data);
    return data
    // await new Promise(resolve => setTimeout(resolve,3000))
    // commit('setLoading',false)//结束
};
// 封装 post 请求
const postAndCommit = async (
    url: string,
    mutationName: string,
    commit: Commit,
    payload: any
) => {
    const {data} = await axios.post(url, payload);
    commit(mutationName, data);
};

const asyncAndCommit = async (url: string, mutationName: string, commit: Commit, config: AxiosRequestConfig = {method: "get"}) => {
    const {data} = await axios(url, config);
    commit(mutationName, data);
    return data
}

// import {testData, testProps} from "@/testData";

export interface ImageProps {
    _id?: string;
    url?: string;
    createdAt?: string
}

export interface UserProps {
    //当前是否登录
    isLogin: boolean;
    nickName?: string;
    _id?: string;
    column?: string; //用户自己的专栏Id
    avatar?: ImageProps;
    description?: string
}


export interface ColumnProps {
    // 专栏列表
    _id: string;
    title: string; //标题
    avatar?: ImageProps; //头像
    description: string; //描述
}

export interface PostProps {
    // 文章列表
    _id?: string;
    title: string;
    excerpt?: string;
    content?: string; //内容
    image?: ImageProps | string; //图片
    createdAt?: string; //发布时间
    column: string;
    author?: string | UserProps//文章id 因为你点开的那个文章要和你的文章id做匹配
}

// 声明错误
export interface GlobalErrorProps {
    stateus: boolean//控制显示隐藏
    message?: string
}

export interface ResponseType<p = []> {
    code: number,
    msg: string,
    data: p
}

// 如果你想在其他页面使用的话导出就可以了
export interface GolbalDataProps {
    columns: ColumnProps[];
    posts: PostProps[];
    user: UserProps;
    loading: boolean;
    token: string;
    error: GlobalErrorProps
}

const store = createStore<GolbalDataProps>({
    state: {
        columns: [],
        posts: [],
        user: {isLogin: false},
        loading: false,
        token: localStorage.getItem("token") || "",
        error: {stateus: false}
    },
    //Vuex允许我们在store中定义'getter' (可以认为是store的计算属性)
    //getter 的返回值会根据他的依赖被缓存起来，且只有当它的依赖值发生了改变才会被重新计算
    getters: {

        // biggerColumnsLen(state){
        //   return state.columns.filter(c => c.id >2).length
        // },
        // 当前跳转的专栏详情是否是我点击的专栏
        // 专栏详情
        getColumnById: (state) => (id: string) => {
            return state.columns.find((c) => c._id === id);
        },
        // 文章列表
        getPostById: (state) => (cid: string) => {
            return state.posts.filter((post) => post.column === cid);
        },
        getPost: (state) => (id: number) => {
            // return state.posts.find(post => post.column === id)
            return state.posts[id]
        }
    },
    mutations: {
        // 登录
        login(state, rwaData) {
            // state.token = rwaData.data.token
            const {token} = rwaData.data;
            state.token = token;
            localStorage.setItem("token", token);
            axios.defaults.headers.common.Authorization = ` Bearer ${token}`;
            //   state.user = { ...state.user, isLogin: true, nickName: "郭好好" };
        },
        logout(state) {
            state.token = ''
            localStorage.removeItem('token')
            delete axios.defaults.headers.common.Authorization
        },
        // 获取用户信息
        fetchCurrentUser(state, rwaData) {
            state.user = {isLogin: true, ...rwaData.data};
        },
        createPost(state, newPost) {
            state.posts.push(newPost);
            // 新建文章
        },
        // 专栏列表
        fetchColumns(state, rwaData) {
            state.columns = rwaData.data.list;
        },
        // 专栏详情
        fetchColumn(state, rwaData) {
            state.columns = [rwaData.data];
        },
        // 文章列表
        fetchPosts(state, rwaData) {
            state.posts = rwaData.data.list;
        },
        //文章详情
        fetchPost(state, rwaData) {
            // console.log(rwaData)
            // state.posts = [rwaData.data];
            state.posts[rwaData.data._id] = rwaData.data
        },
        //更新文章
        updatePost(state, {data}) {
            state.posts = state.posts.map(post => {
                if (post._id === data._id) {
                    return data
                } else {
                    return post
                }
            })
        },
        deletePost(state,{data}){
          state.posts = state.posts.filter(post => post._id !== data.id
          )
        },
        // 控制loading 效果显示和隐藏
        setLoading(state, status) {
            state.loading = status; //true 和 false的值
        },
        // 消息错误提示
        setError(state, e: GlobalErrorProps) {
            state.error = e
        }
    },
    // action 类似于 mutation
    // action 提交的是mutation，而不是直接改变状态
    // mutation的方法是唯一一个可以修改以上数据的
    actions: {
        // 专栏列表
        async fetchColumns(context) {
            // axios.get('/columns').then(resp => {
            //     context.commit('fetchColumns', resp.data)
            // })

            // const {data} = await axios.get('/columns')
            // context.commit('fetchColumns', data)

            // getAndCommit("/columns", "fetchColumns", context.commit);
            asyncAndCommit("/columns", "fetchColumns", context.commit);
        },
        // 专栏详情
        async fetchColumn({commit}, cid) {
            // axios.get(`/columns/${cid}`).then(resp => {
            //     commit('fetchColumn', resp.data)
            // })

            // const {data} = await axios.get(`/columns/${cid}`)
            // commit('fetchColumns', data)

            getAndCommit(`/columns/${cid}`, "fetchColumn", commit);
        },
        // 文章列表
        async fetchPosts({commit}, cid) {
            //   axios.get(`/columns/${cid}/posts`).then(resp => {
            //     commit('fetchPosts',resp.data)
            //   })

            // const {data} = await axios.get(`/columns/${cid}/posts`)
            // commit('fetchColumns', data)

            getAndCommit(`/columns/${cid}/posts`, "fetchPosts", commit);
        },
        // async fetchPost({commit},cid){
        //     getAndCommit(`/posts/${cid}`,"fetchPost",commit)
        // },
        fetchPost({state, commit}, id) {
            const currentPost = state.posts[id]
            if (!currentPost || !currentPost.content) {
                return getAndCommit(`/posts/${id}`, "fetchPost", commit)
            } else {
                return Promise.resolve({data: currentPost})
            }
        },
        updatePost({commit}, {id, payload}) {
            return asyncAndCommit(`/posts/${id}`, 'updatePost', commit, {
                method: 'patch',
                data: payload
            })
        },
        //删除文章
        deletePost({commit},id){
            return asyncAndCommit(`/posts/${id}`,'deletePost',commit,{method:'delete'})
        },
        // 登录
        login({commit}, payload) {
            return postAndCommit("/user/login", "login", commit, payload);
        },
        fetchCurrentUser({commit}) {
            // 提交一个mutations方法
            getAndCommit("/user/current", "fetchCurrentUser", commit);
        },
        // 先登录在获取用户信息
        // 给登录和获取信息排请求顺序
        loginAndFecth({dispatch}, loginData) {
            return dispatch("login", loginData).then(() => {
                return dispatch("fetchCurrentUser");
            });
        },
        createPost({commit}, payload) {
            return postAndCommit("/posts", "createPost", commit, payload);
        },

    },
    modules: {},
});

export default store;
